<template>
  <div class="flex w-full   h-auto my-2 mb-2 py-2 mx-2 my-1">
    <!-- 1.查询的展示 -->
    <div class="bg-white my-2 mb-2 pt-1 mr-4 mt-2 flex-1 min-w-0 rounded-md shadow-sm">
      <div class="mt-2 mr-4 my-4">
        <BasicForm @register="registerQueryForm" @submit="fetchQueryData">
        </BasicForm>
        <BasicTable @register="registerQueryTable"></BasicTable>
      </div>
    </div>
    <!-- 2.excel上传的文件展示 -->
    <div class="bg-white my-2 mb-2 pt-1 pb-4 mr-4 mt-2 flex-1 min-w-0 rounded-md shadow-sm">
      <div class="mt-2">
        <!-- 表单区域 -->
        <div>
          <BasicForm @register="registerExcelForm">
            <!-- 添加自定义上传按钮插槽 -->
            <template #buttonGroup>
              <div class="flex items-center pt-2">
                <input
                    type="file"
                    ref="fileInput"
                    @change="handleFileUpload"
                    accept=".xlsx,.xls"
                    style="display: none"
                />
                <a-space size="middle">
                  <a-button type="primary" @click="triggerFileUpload">1.上传Excel文件</a-button>
                  <a-button type="primary" @click="handleSave" >2.保存</a-button>
                </a-space>
              </div>
            </template>

          </BasicForm>
          <div class="bg-red-50 p-3 rounded-md mb-8 text-sm text-red-700 border border-red-200">
            <span class="font-bold">提示：</span>当前导入/修改数据日期为：{{ currentDate }}。<br/>
            <span>请核对下面输入框中的数值是否与"前夜填报excel"中一致，如果数值不正确请在输入框中修改后点击"保存"按钮。</span>
          </div>
          <!-- 表单部分 -->
          <a-form
              :model="formState"
              layout="horizontal"
              :label-col="{ span: 8 }"
              :wrapper-col="{ span: 16 }"
              class="mx-auto mx-4 my-4"
              style="max-width: 800px;"
          >
            <a-form-item
                v-for="(item, index) in formItems"
                :key="index"
                :label="item.label"
                :name="item.name"
            >
              <a-input
                  v-model:value="formState[item.name]"
                  placeholder="请输入数值"
                  @change="validateItemValue(item.name)"
                  style="width: 40%; font-size: 16px;"
              />
                <span v-if="formErrors[item.name]" class="text-red-500 ml-2">
                  <span class="anticon anticon-warning mr-1"></span>
                  {{ formErrors[item.name] }}
                </span>
            </a-form-item>
          </a-form>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import {defineComponent, ref, reactive, onMounted, onBeforeMount} from 'vue';
import { BasicTable, useTable } from '/@/components/Table';
import { BasicForm, useForm } from '/@/components/Form/index';
import * as XLSX from 'xlsx';
// 导入配置和工具函数
import {
  excelImportFormSchema, timeSeriesExcelDataShowQueryConditionFormShame, timeSeriesExcelDataShowTableColumns,
} from './exceldata.data';
import { savePointNumberDatas, queryPointNumberDatas,queryfixedPointNumberDatas,getPoints,queryPoints } from "/@/api/demo/timeseries";
import dayjs from 'dayjs';
import {
  TSNumDataDto,
  TSNumDataFixedQueryConditionDto,
  TSNumDataQueryConditionDto,
} from "/@/api/demo/model/timeSeriesModel";
import { useMessage } from "/@/hooks/web/useMessage";
const { createMessage } = useMessage();
import { useRouter } from 'vue-router';

export default defineComponent({
  name: 'ExcelImportAndDisplay',
  components: { BasicForm, BasicTable },

  setup() {
    const router = useRouter();

    // 动态表单项，将根据URL参数动态生成
    const formItems = ref([]);

    // 动态生成的表单状态对象
    const formState = reactive({});

    // 动态生成的表单错误信息对象
    const formErrors = reactive({});
    // 验证单个字段
    const validateItemValue = (field: string) => {
      const value = formState[field];
      if (value === '') {
        return true;
      } else if (!/^-?\d*\.?\d+$/.test(String(value))) {
        formErrors[field] = '包含非数字字符，请修正';
        return false;
      } else {
        formErrors[field] = '';
        return true;
      }
    };

    // 验证整个表单
    const validateForm = () => {
      let isValid=true;
      let allEmpty = true; // 用于检查是否所有字段都为空

      for (const item of formItems.value) {
        const value= formState[item.name]
        if (value !== undefined && value !== '') {
          allEmpty = false;

          //只验证非空字段的格式
          if (!/^-?\d*\.?\d+$/.test(String(value))){
            formErrors[item.name]='包含非数字字符，请修正'
            isValid=false;
          }else{
            formErrors[item.name]=''
          }
        }else{
          formErrors[item.name]=''
        }
      }
      return { isValid, allEmpty };
    };

    const fileInput = ref<HTMLInputElement | null>(null);
    const fileName = ref<string>('');
    const currentDate = ref(dayjs().format('YYYY-MM-DD'));
    const fixedPointIds =ref() ; // 硬编码的点号IDs，现在设为常量

    // ===== 点号数值展示区域 ======
    const [registerQueryForm, { getFieldsValue , updateSchema }] = useForm({
      labelWidth: 80,
      schemas: timeSeriesExcelDataShowQueryConditionFormShame,
      showResetButton: false,
      showSubmitButton: true,
      showIndexColumn: true,

    });

    const [registerQueryTable, { setTableData: setQueryTableData }] = useTable({
      title: '查询数据展示',
      columns: timeSeriesExcelDataShowTableColumns,
      canResize: true,
      bordered: true,
      striped: true,
      size: 'default',
      showIndexColumn: true,
      // 添加以下配置自定义序号列
      indexColumnProps: {
        width: 30,  // 设置序号列宽度为 80px
        title: '序号'  // 自定义序号列标题
      },
      pagination: false
    });

    // ===== excel区域表单 ======
    const [registerExcelForm] = useForm({
      labelWidth: 80,
      schemas: excelImportFormSchema,
      showResetButton: false,
      showSubmitButton: false,
      showIndexColumn: true,
      labelAlign: 'right',
      rowProps: {
        gutter: 10,
      },
    });

    // 初始化表单数据
    function initializeFormData() {
      // 根据动态生成的表单项初始化表单数据
      formItems.value.forEach(item => {
        formState[item.name] = '';
        formErrors[item.name] = '';
      });
    }

    // 获取表单日期
    async function getFormDate  () {
      // 设置组件已卸载标志 - 这行很重要！

      try {
        const queryValues = await getFieldsValue();

        const dateVal = queryValues.date; // 获取日期
        if (dateVal) {
          currentDate.value = dayjs(dateVal).format('YYYY-MM-DD');
        }
        return dateVal;
      } catch (error) {
        console.log('表单验证失败', error);
        return null;
      }
    }

    // 查询数据
    async function fetchQueryData() {
      try {
        // 获取表单数据
        const formValues = getFieldsValue();

        const date = formValues.date ||dayjs().startOf('day').toDate();
        currentDate.value = dayjs(date).format('YYYY-MM-DD');

        if (!fixedPointIds.value || fixedPointIds.value.length === 0) {

          // 检查是否有url的参数中的点号
          let fullPathArray = router.currentRoute.value.fullPath.split('/');
          let notEmptyPathArray=fullPathArray.filter((str)=>str.length>0)

          //如果URL中有点号参数，直接使用
          if (notEmptyPathArray.length>2){
            let urlPointds=notEmptyPathArray.slice(2);

            //使用getPoints方法查询点号详细信息
            const pointIdsStr = urlPointds.join(',');
            const pointsInfo=await getPoints(pointIdsStr);

            if (pointsInfo && pointsInfo.length>0){
              //凑够查询结果中提取点号ID
              fixedPointIds.value=pointsInfo.map(point => point.pointid);
            }else {
              createMessage.error('未能获取到点号详细信息')
              return;
            }
          }else{
            //否则查询所有点号
            try {
              const res =await queryPoints(null)
              if (res && res.length>0){
                fixedPointIds.value=res.map(item=>item.pointid)
              }else {
                createMessage.error('没有点号，请先创建点号');
                return;
              }
            }catch (error){
              console.error('获取点号失败:', error);
              createMessage.error('获取点号列表失败: ' + ((error as Error).message || '未知错误'));
              return;
            }
          }
        }
        // 确保已经有点号后再进行查询
        if (!fixedPointIds.value || fixedPointIds.value.length === 0) {
          createMessage.error('没有可用的点号，无法查询数据');
          return;
        }

        // 准备查询参数
        const pointIdsToQuery = fixedPointIds.value.join(',').split(',')
            .map(item => item.trim())
            .filter(item => item !== '');

        if (pointIdsToQuery.length === 0) {
          createMessage.error('没有有效的点号，请先创建点号');
          return;
        }

        const queryParams: TSNumDataFixedQueryConditionDto = {
          pointids: pointIdsToQuery,
          tm: dayjs(date).startOf('day').format('YYYY-MM-DD HH:mm:ss'),
        };

        // 调用查询API获取数据
        const response = await queryfixedPointNumberDatas(queryParams);
        if (response.length<=0){
          initializeFormData()
          return;
        }
        // 检查格式是否符合预期
        if(!response || !response.datas) {
          console.error('查询返回数据格式错误:', response);
          createMessage.error('查询数据返回格式错误');
          initializeFormData();
          setQueryTableData([]);
          return;
        }

        const {datas,points}=response;

        //检查是否有数据
        if (!datas || !Array.isArray(datas)|| datas.length===0){
          initializeFormData();
          setQueryTableData([]);
          return;
        }
        // 根据点号ID创建一个映射，方便快速查找点号信息
        const pointsMap = {};
        if (points && Array.isArray(points)) {
          points.forEach(point => {
            if (point && point.pointid) {
              pointsMap[point.pointid] = point;
            }
          });
        }
          const pointIdsFromResponse = datas.map(item => item.pointid);

          // 初始化表单数据
          initializeFormData()

        // 处理表格显示数据，确保 NaN 值显示为空字符串并按照相同的顺序排序
        const sortedPoints = [...points].sort((a, b) => {
          const orderA = a.odr || 999;
          const orderB = b.odr || 999;
          return orderA-orderB  ; // 使用相同的降序排序逻辑
        });
          // 处理表格显示数据，确保 NaN 值显示为空字符串
          const processedResponse =[]
        sortedPoints.forEach(point  => {
          // 找到对应的数据项
          const dataItem = datas.find(item => item.pointid === point.pointid);
          if (dataItem) {
            processedResponse.push({
              value: isNaN(Number(dataItem.value)) ? '' : dataItem.value,
              pointid: point.pointid,
              pointname: point.pointname,
              unit: point.unit || '',
              intm:dataItem.intm
            });
          }
          });

          // 更新查询结果数据
          setQueryTableData(processedResponse);

        // 动态生成表单项 - 基于实际查询结果
        generateDynamicFormItems(pointIdsFromResponse,sortedPoints);

          datas.forEach((item) => {
            // 使用点号ID作为字段名
            const fieldName = item.pointid;
              //如果表单中存在这个字段，则设置值
              if (formState.hasOwnProperty(fieldName)){
                //检查值是否为NaN
                if (item.value === "NaN" || isNaN(Number(item.value))) {
                  formState[fieldName] = '';
                } else {
                  formState[fieldName] = String(item.value);
                }
                validateItemValue(fieldName)
              }
          })
      } catch (error) {
        console.error('查询数据时出错:', error);
        createMessage.error('查询数据失败: ' + ((error as Error).message || '未知错误'));
        initializeFormData();
        setQueryTableData([]);
      }
    }

    // 触发文件上传
    function triggerFileUpload() {
      if (fileInput.value) {
        fileInput.value.value = '';
        fileInput.value.click();
      }
    }

    // 处理文件上传
    function handleFileUpload(event: Event) {
      const target = event.target as HTMLInputElement;
      if (!target.files || target.files.length === 0) return;

      const file = target.files[0];
      fileName.value = file.name;

      const reader = new FileReader();
      reader.onload = (e) => {
        if (!e.target) return;

        try {
          // 读取Excel文件内容
          const data = new Uint8Array(e.target.result as ArrayBuffer);

          const workbook = XLSX.read(data, { type: 'array' });

          const targetSheetName = "大屏幕显示";
          if (!workbook.SheetNames.includes(targetSheetName)) {
            createMessage.error(`未找到名为"${targetSheetName}"的工作表`);
            return;
          }

          const worksheet = workbook.Sheets[targetSheetName];
          // 定义Excel单元格与点号的映射
          const cellToPointIdMap = {};

          // 遍历表单项，利用点号信息中的loc属性(如存在)来创建映射
          console.log("formItems.value=======>", formItems.value)
          formItems.value.forEach(item=>{
            //获取对应的点号信息
            const pointId=item.originalPointId || item.name;

            //从一查询的大号信息中查找单元格位置
            // 假设我们已经在formItems中存储了点号的Loc信息
            const loc =item.loc || '';
            if (loc && loc.trim() !== ''){
              cellToPointIdMap[loc]=pointId;
            }
          })
          console.log('cellToPointIdMap:', cellToPointIdMap);

          // 如果没有找到任何映射关系(或者没有loc信息)，则使用默认映射
          if (Object.keys(cellToPointIdMap).length === 0) {

          }
          // 更新Excel单元格数据到表单
          Object.entries(cellToPointIdMap).forEach(([cell, pointId]) => {
            const cellValue = worksheet[cell];
            const rawValue = cellValue ? cellValue.v : "";

            // 直接检查表单状态中是否有对应的字段（点号ID）
            if (formState.hasOwnProperty(pointId)) {
              formState[pointId] = rawValue.toString();
              validateItemValue(pointId);
            }
          });

        } catch (error) {
          console.error('处理Excel文件时出错:', error);
          createMessage.error('Excel文件处理失败: ' + ((error as Error).message || '未知错误'));
        }
      };
      reader.readAsArrayBuffer(file);
    }

    // 添加保存功能
    async function handleSave() {
      try {
        //验证表单
        const {isValid,allEmpty}=validateForm()

        // 如果所有字段都为空，提示用户
        if (allEmpty) {
          createMessage.warning('所有输入框都为空，没有数据需要保存');
          return;
        }

        // 验证表单
        if (!isValid) {
          createMessage.warning('表单中存在错误输入，请先修正后再保存');
          return;
        }

        // 获取表单中的日期
        const dateVal = await getFormDate();
        if (!dateVal) {
          createMessage.warning('无法获取日期，请选择日期后再保存');
          return;
        }

        // 创建保存数据
        const saveData = [];
        // 遍历表单项，直接从表单项中获取点号信息
        formItems.value.forEach(item => {
          const pointId = item.name; // 直接使用name作为pointId
          const value = formState[pointId];

          // 只保存有值的字段
          if (value !== undefined && value !== '') {
            saveData.push({
              // 按照API期望的模型结构创建保存数据
              pointid:pointId,
              value:Number(value),
              tm:dayjs(dateVal).format('YYYY-MM-DD HH:mm:ss'),//确保日期格式正确
            });
          }
        });

        // 调用API保存数据
        const res = await savePointNumberDatas(saveData);
        if (!res || Object.keys(res).length == 0)  {
          createMessage.success('保存成功');
          await fetchQueryData();
        }
      } catch (error) {
        console.error('保存数据时出错:', error);
        createMessage.error('保存数据失败: ' + (error.message || '未知错误'));
      }
    }

    function generateDynamicFormItems(pointIdsArray,pointsData) {
      // 清空之前的表单项
      formItems.value = [];

      // 动态为表单状态和错误对象添加属性
      const newFormState = {};
      const newFormErrors = {};

      // 找出响应数据中对应的点号信息
      if (Array.isArray(pointsData)){

        // 根据排序后的数据生成表单项
        pointsData.forEach(point  => {
          if (point && pointIdsArray.includes(point.pointid)){
            //为每个点号创建一个唯一的字段名
            const fieldName = point.pointid;

            //添加到表单项数组
            formItems.value.push({
              name: fieldName,
              label:  point.unit && point.unit.trim() !== ''
                  ? `${point.pointname}(${point.unit})`:point.pointname,

              originalPointId: point.pointid, // 保存原始点号
              unit: point.unit || '', // 保存单位信息
              loc: point.loc || '', // 保存Excel单元格位置信息，用于文件上传
            })

            //为表单状态和错误对象添加对应的属性
            newFormState[fieldName] = '';
            newFormErrors[fieldName] = '';
          }
        });
      }
      // 如果没有生成任何表单项（可能是因为没有匹配的点号），可以添加默认处理
      if (formItems.value.length === 0) {
        console.warn('没有找到匹配的点号信息，无法生成表单项');
      }

      // 更新表单状态和错误对象
      Object.keys(newFormState).forEach(key => {
        formState[key] = newFormState[key];
      });

      Object.keys(newFormErrors).forEach(key => {
        formErrors[key] = newFormErrors[key];
      });
    }

    onBeforeMount( ()=>{
      console.log('TimeSeries NumberData Index.vue onBeforeMount');
    })

    onMounted(() => {
      updateSchema({
        field: 'date',
        componentProps: {
          ...timeSeriesExcelDataShowQueryConditionFormShame[0].componentProps,
          onChange: (value) => {
            if (value) {
              // 当日期选择器值变化时，立即更新 currentDate
              currentDate.value = dayjs(value).format('YYYY-MM-DD');
            }
          }
        }
      });

      // 获取当前表单值，并确保 currentDate 初始同步
      const formValues = getFieldsValue();
      if (formValues && formValues.date) {
        currentDate.value = dayjs(formValues.date).format('YYYY-MM-DD');
      }

      fetchQueryData();
    });
    return{
      registerQueryForm,
      registerQueryTable,
      registerExcelForm,
      handleFileUpload,
      fetchQueryData,
      triggerFileUpload,
      fileInput,
      fileName,
      currentDate,
      handleSave,
      formState,
      formItems: formItems,
      formErrors,
      validateItemValue,
    }
  }
})
</script>
